import fs from 'fs';
import axios from 'axios';

async function downloadImage(url, dest) {
    try {
        // 发送HTTP GET请求获取图片数据
        const response = await axios({
            url,
            method: 'GET',
            responseType: 'stream'
        });

        // 创建一个可写流用于写入文件
        const writer = fs.createWriteStream(dest);

        // 将响应流管道化到文件
        response.data.pipe(writer);

        // 监听完成事件
        return new Promise((resolve, reject) => {
            writer.on('finish', resolve);
            writer.on('error', reject);
        });
    } catch (error) {
        console.error('Error downloading image:', error);
        throw error;
    }
}
